package DBLayer;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import ModelLayer.Customer;

public class CustomerDB
{
    private  Connection conn;

    public CustomerDB()
    {
    	conn = ConnectionDB.getInstance().getDBcon();
    }
    
    /**
     * Indsætter customer i db.
     * @param c
     */
    public void createCustomer(Customer c) throws SQLException
    {
    	String query = "insert into Customer values ('"+c.getName()+"', '"+c.getAddress()+"', '"+c.getZipcode()+"', '"+c.getPhoneNo()+"')";
    	
    	try
    	{
    		Statement stmt = conn.createStatement();
    		stmt.setQueryTimeout(5);
    		stmt.executeUpdate(query);
    	}
    	catch (SQLException e)
    	{
    		throw e;
    	}
    }

    /**
     * Finder en customer ud fra telefon nr.
     * @param phoneno	telefon nr.
     * @return	et customer objekt.
     */
    public Customer findCustomer(String phoneno)
    {
    	String query = "SELECT name, address, C.zipcode, phoneno, city FROM Customer as C, City" +
    			" WHERE C.phoneno=" + phoneno + " AND City.zipcode=C.zipcode";
    	Customer c = null;
    	
    	try
		{
			// Udfør query på databasen.
			Statement stmt = conn.createStatement();
			stmt.setQueryTimeout(5);
			ResultSet results = stmt.executeQuery(query);
			
			// Tag første resultat ud af db.
			c = buildCustomer(results);
			
			return c;
		}
		catch (SQLException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    	return null;
    }
    
    /**
     * Laver ét customer objekt ud et ResultSet. Hvis der er fundet flere tupler, så bliver kun den første fundne returneret.
     * @param result
     * @return
     * @throws SQLException
     */
    public Customer buildCustomer(ResultSet result) throws SQLException
    {
    	Customer c = null;
    	
    	if (result.next())
		{
			// Opret en customer.
			c = new Customer(result.getString("name"),
					result.getString("address"),
					result.getInt("zipcode"),
					result.getString("city"),
					result.getString("phoneno"));
		}
    	
    	return c;
    }
    
    public int getCustomerId(int phoneno)
    {
    	//TODO.
    	return 0;
    }
}
